<template>
  <!-- 字典项 -->
  <FormTableCardComp>
    <template #form>
      <t-form ref="form" :data="dictSearch" scroll-to-first-error="smooth" layout="inline" colon @reset="onReset"
        @submit="onSubmit">
        <t-form-item labelWidth="0" name="name">
          <t-input v-model="dictSearch.name" placeholder="请输入字典名称或字典编码"></t-input>
        </t-form-item>
        <t-form-item labelWidth="0">
          <t-space size="small">
            <t-button theme="primary" type="submit">提交</t-button>
            <t-button theme="default" variant="base" type="reset">重置</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </template>
    <template #table>
      <t-table v-model:columnControllerVisible="dictState.columnControllerVisible" row-key="dictId"
        :data="dictState.tableData" :columns="columns" lazy-load bordered
        :pagination="{ defaultPageSize: 5, defaultCurrent: 1, total: 100000 }"
        :column-controller="columnControllerConfig" :loading="dictState.loading">
        <template #topContent>
          <TableToolbar>
            <template #toolbarLeft>
              <t-button theme="primary" @click="dictEdit('add')">
                新增
              </t-button>
            </template>
            <template #toolbarRight>
              <t-tooltip content="刷新">
                <t-button shape="circle" variant="text">
                  <template #icon>
                    <RefreshIcon />
                  </template>
                </t-button>
              </t-tooltip>
              <t-tooltip content="列表配置">
                <t-button shape="circle" variant="text" @click="dictState.columnControllerVisible = true">
                  <template #icon>
                    <SettingIcon />
                  </template>
                </t-button>
              </t-tooltip>
            </template>
          </TableToolbar>
        </template>

        <template #dictType="{ row }">
          <t-link theme="primary" @click="toDictDataView(row)">{{ row.dictType }}</t-link>
        </template>

        <template #status="{ row }">
          <re-status :status="row.status" />
        </template>

        <template #options="{ row }">
          <t-space size="small">
            <t-link theme="primary" @click="dictEdit('edit', row)"> 编辑 </t-link>
            <t-popconfirm v-model="dictState.delConfirmVisible" theme="danger" content="确定删除该字典"
              @confirm="delDict(row)">
              <t-link theme="danger"> 删除 </t-link>
            </t-popconfirm>
          </t-space>
        </template>
      </t-table>
    </template>
  </FormTableCardComp>

  <!-- 字典项编辑 -->
  <t-dialog v-model:visible="dictState.dictVisible" :header="dictState.dictEditTitle" @confirm="dictSubmit"
    @closed="dictClose">
    <t-form ref="dictFormRef" :data="dictState.dictRow" :rules="dictRules" scroll-to-first-error="smooth" colon>

      <t-form-item label="字典名称" name="dictName">
        <t-input v-model="dictState.dictRow.dictName" placeholder="请输入字典名称" />
      </t-form-item>
      <t-form-item label="字典编码" name="dictType">
        <t-input v-model="dictState.dictRow.dictType" placeholder="请输入字典编码" />
      </t-form-item>
      <t-form-item label="备注" name="remarks">
        <t-textarea v-model="dictState.dictRow.remarks" placeholder="请输入备注" :autosize="{ minRows: 5, maxRows: 5 }" />
      </t-form-item>
      <t-form-item label="状态" name="status">
        <t-switch v-model="dictState.dictRow.status" :label="['有效', '无效']" :custom-value="[0, 1]" />
      </t-form-item>

    </t-form>
  </t-dialog>

  <!-- 字典数据 -->
  <t-drawer v-model:visible="dictDataState.drawer.visible" :header="dictDataState.drawer.dictName" :footer="false"
    close-btn size="45%" @close="dictDataDrawerClose">
    <FormTableCardComp>
      <template #form>
        <t-form :data="dictDataState.search" layout="inline" @reset="onReset" @submit="onSubmit">
          <t-row :gutter="[0, 15]">
            <t-col :span="6">
              <t-form-item label="字典标签" name="dictLabel">
                <t-input v-model="dictDataState.search.dictLabel" placeholder="请输入字典标签"></t-input>
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="字典值" name="dictValue">
                <t-input v-model="dictDataState.search.dictValue" placeholder="请输入字典值"></t-input>
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="状态" name="status">
                <t-select v-model="dictDataState.search.status" clearable>
                  <t-option v-for="(item, index) in COMMON_STATUS" :key="index" :value="item.value" :label="item.label">
                    {{ item.label }}
                  </t-option>
                </t-select>
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item labelWidth="0">
                <t-space size="small">
                  <t-button theme="primary" type="submit">提交</t-button>
                  <t-button theme="default" variant="base" type="reset">重置</t-button>
                </t-space>
              </t-form-item>
            </t-col>
          </t-row>

        </t-form>
      </template>
      <template #table>
        <t-table row-key="dictDataId" :data="dictDataState.table.tableData" :columns="dictDataTableColumns" lazy-load
          bordered :pagination="{ defaultPageSize: 10, defaultCurrent: 1, PageSize: 10, total: 20 }"
          :loading="dictDataState.table.loading">
          <template #topContent>
            <TableToolbar>
              <template #toolbarLeft>
                <t-button theme="primary" @click="dictDataEdit('add')">
                  <template #icon> <add-icon /></template>
                  新增
                </t-button>
              </template>
              <template #toolbarRight>
                <t-tooltip content="刷新">
                  <t-button shape="circle" variant="text">
                    <template #icon>
                      <RefreshIcon />
                    </template>
                  </t-button>
                </t-tooltip>
              </template>
            </TableToolbar>
          </template>

          <template #dictCode="{ row }">
            <t-link theme="primary" @click="toDictDataView(row)">{{ row.dictCode }}</t-link>
          </template>

          <template #status="{ row }">
            <re-status :status="row.status" />
          </template>

          <template #options="{ row }">
            <t-space size="small">
              <t-link theme="primary" @click="dictDataEdit('edit', row)"> 编辑 </t-link>
              <t-popconfirm v-model="dictDataState.delConfirmVisible" theme="danger" content="确定删除该字典"
                @confirm="delDictData(row)">
                <t-link theme="danger"> 删除 </t-link>
              </t-popconfirm>
            </t-space>
          </template>

        </t-table>
      </template>
    </FormTableCardComp>
  </t-drawer>

  <!-- 字典数据编辑 -->
  <t-dialog v-model:visible="dictDataState.form.visible" :header="dictDataState.form.title" @confirm="dictDataSubmit"
    @closed="dictDataClose">
    <t-form ref="dictDataFormRef" :data="dictDataState.form.row" :rules="dictDataRules" scroll-to-first-error="smooth"
      colon>
      <t-form-item label="字典标签" name="dictLabel">
        <t-input v-model="dictDataState.form.row.dictLabel" placeholder="请输入字典标签" autocomplete="off" />
      </t-form-item>
      <t-form-item label="字典键值" name="dictValue">
        <t-input v-model="dictDataState.form.row.dictValue" placeholder="请输入字典键值" autocomplete="off" />
      </t-form-item>
      <t-form-item label="字典类型" name="dictType">
        <t-input v-model="dictDataState.form.row.dictType" readonly />
      </t-form-item>
      <t-form-item label="字典排序" name="dictSort">
        <t-input-number v-model="dictDataState.form.row.dictSort" :min="1" :max="1000" />
      </t-form-item>
      <!-- <t-form-item label="回显样式" name="listClass">
        <t-input-number v-model="dictDataState.form.row.listClass" :min="1" :max="1000" />
      </t-form-item> -->
      <t-form-item label="状态" name="status">
        <t-switch v-model="dictDataState.form.row.status" :label="['有效', '无效']" :custom-value="[0, 1]" />
      </t-form-item>

    </t-form>
  </t-dialog>

</template>

<script setup lang="ts">
import { SysDict, SysDictData } from '@/api/model/sys';
import { FormTableCardComp } from '@/components/ReCard';
import { ReStatus } from '@/components/ReStatus';
import { TableToolbar } from '@/components/ReTable';
import { AddIcon, RefreshIcon, SettingIcon } from 'tdesign-icons-vue-next';
import { FormInstanceFunctions, FormProps, FormRules, MessagePlugin } from 'tdesign-vue-next';
import { PrimaryTableCol } from 'tdesign-vue-next/es/table/type';
import { COMMON_STATUS } from '@/constants/common';

// ---------------------------------------
const dictSearch = reactive({
  name: '',
})

const onReset: FormProps['onReset'] = () => {
  MessagePlugin.success('重置成功');
};
const onSubmit: FormProps['onSubmit'] = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    MessagePlugin.success('提交成功');
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError as string);
  }
};

interface dictStateType {
  loading: boolean;
  columnControllerVisible: boolean;
  tableData: Array<SysDict>,
  //
  dictEditTitle: string,
  dictVisible: boolean,
  dictRow: SysDict,
  // 删除
  delConfirmVisible: boolean,
}

const dictState = reactive<dictStateType>({
  loading: false,
  columnControllerVisible: false,
  tableData: [
    {
      dictId: '1',
      dictName: '测试111',
      dictType: 'Test1',
      remarks: '备注',
      status: 0,
      createTime: '2022-01-01',
      updateTime: '2022-01-01',
      createBy: 'admin',
      updateBy: 'admin',
    }
  ],
  //
  dictEditTitle: '',
  dictVisible: false,
  dictRow: {
    dictId: '',
    dictName: '',
    dictType: '',
    remarks: '',
    status: 0,
    createTime: '',
    updateTime: '',
    createBy: '',
    updateBy: '',
  },
  // 删除
  delConfirmVisible: false,
});

// @ts-ignore
const columns: Array<PrimaryTableCol<SysDict>> = [
  { colKey: 'serial-number', width: '60', title: '序号', align: 'center', },
  {
    colKey: 'dictName',
    title: '字典名称',
    width: '250',
  },
  {
    colKey: 'dictType',
    title: '字典编码',
    width: '250',
  },
  {
    colKey: 'remarks',
    title: '备注',
    width: '200',
  },
  {
    colKey: 'status',
    title: '状态',
    width: '50',
    align: 'center'
  },
  {
    colKey: 'options',
    title: '操作',
    width: '200',
    fixed: 'right',
  },
];

// 列配置
const columnControllerConfig = computed(() => ({
  hideTriggerButton: true,
  // 允许哪些列参与显示-隐藏控制
  fields: ['dictName', 'dictCode', 'remarks',],
  // 透传弹框组件全部属性
  dialogProps: { preventScrollThrough: true },
}));

const dictFormRef = ref<FormInstanceFunctions<SysDict>>();

// 校验规则
const dictRules: FormRules<any> = {
  dictName: [
    { required: true, message: '请输入字典名称', type: 'error' },
    { max: 20, message: '字典名称应在20字以内', type: 'error', trigger: 'blur' },
  ],
  dictType: [
    { required: true, message: '请输入字典编码', type: 'error' },
    { max: 20, message: '字典编码应在20字以内', type: 'error', trigger: 'blur' },
  ],
  remarks: [
    { min: 0, max: 200, message: '备注在200字以内', type: 'error', trigger: 'blur' },
  ],
}

const dictEdit = (type: string, row?: any) => {
  if (type === 'add') {
    dictState.dictEditTitle = '新增字典';
    dictState.dictVisible = true;
  } else if (type === 'edit') {
    dictState.dictEditTitle = '编辑字典';
    dictState.dictRow = { ...row };
    dictState.dictVisible = true;
  }
  console.log('dictRow', dictState.dictRow);
}

const dictSubmit = () => {
  dictFormRef.value?.validate().then((validateResult) => {
    if (validateResult === true) {
      MessagePlugin.success('提交成功');
      dictState.dictVisible = false;
    }
  });
}

const dictClose = () => {
  dictFormRef.value?.reset({
    type: 'initial',
  });
}

const delDict = (res: SysDict) => {
  console.log('delDict', res);

}

const toDictDataView = (row: SysDict) => {
  dictDataState.drawer = {
    visible: true,
    dictName: row.dictName,
  }
  dictDataState.form.row.dictType = row.dictType;
}

// ---------------------------------------

// ---------------------------------------

interface dictDataStateType {
  // 弹窗
  drawer: {
    visible: boolean,
    dictName: string,
  },
  search: {
    dictLabel: string
    dictValue: string
    status: string
  },
  // table
  table: {
    loading: boolean;
    tableData: Array<SysDictData>,
  },
  form: {
    visible: boolean,
    title: string,
    row: SysDictData,
  },
  // 删除
  delConfirmVisible: boolean,
}

const dictDataState = reactive<dictDataStateType>({
  // 弹窗
  drawer: {
    visible: false,
    dictName: '',
  },
  search: {
    dictLabel: '',
    dictValue: '',
    status: '',
  },
  // table
  table: {
    loading: false,
    tableData: [
      {
        dictDataId: '111',
        dictLabel: '测试',
        dictValue: 'test',
        dictType: 'Test1',
        dictSort: 1,
        listClass: '',
        isDefault: 'Y',
        status: 0,
        createTime: '11',
        updateTime: '22',
        createBy: '33',
        updateBy: '44',
      }
    ],
  },
  form: {
    visible: false,
    title: '',
    row: {
      dictDataId: '',
      dictLabel: '',
      dictValue: '',
      dictType: '',
      dictSort: 1,
      listClass: '',
      isDefault: 'Y',
      status: 0,
      createTime: '',
      updateTime: '',
      createBy: '',
      updateBy: '',
    },
  },
  // 删除
  delConfirmVisible: false,
});

// @ts-ignore
const dictDataTableColumns: Array<PrimaryTableCol<SysDictData>> = [
  { colKey: 'serial-number', width: '60', title: '序号', align: 'center', },
  {
    colKey: 'dictLabel',
    title: '字典标签',
    width: '150',
  },
  {
    colKey: 'dictValue',
    title: '字典值',
    width: '150',
  },
  {
    colKey: 'dictSort',
    title: '排序',
    width: '60',
  },
  {
    colKey: 'status',
    title: '状态',
    width: '50',
    align: 'center'
  },
  {
    colKey: 'options',
    title: '操作',
    width: '100',
    fixed: 'right',
  },
];

const dictDataFormRef = ref<FormInstanceFunctions<SysDictData>>();

// 校验规则
const dictDataRules: FormRules<any> = {
  dictLabel: [
    { required: true, message: '请输入字典标签', type: 'error' },
    { max: 20, message: '字典标签应在20字以内', type: 'error', trigger: 'blur' },
  ],
  dictValue: [
    { required: true, message: '请输入字典键值', type: 'error' },
    { max: 40, message: '字典键值应在40字以内', type: 'error', trigger: 'blur' },
  ],
}

const dictDataEdit = (type: string, row?: any) => {
  if (type === 'add') {
    dictDataState.form.title = '新增字典数据';
    dictDataState.form.visible = true;

    // 获取最大值
    // dictDataState.form.row.dictSort = Math.max(...dictDataState.table.tableData.map(item => item.dictSort)) + 1

  } else if (type === 'edit') {
    dictDataState.form.title = '编辑字典数据';
    dictDataState.form.row = { ...row };
    dictDataState.form.visible = true;
  }
  console.log('dictRow', dictDataState.form.row);
}

const dictDataSubmit = () => {
  dictDataFormRef.value?.validate().then((validateResult) => {
    if (validateResult === true) {
      MessagePlugin.success('提交成功');
      dictState.dictVisible = false;
    }
  });
}

const dictDataClose = () => {
  dictDataFormRef.value?.reset({
    type: 'initial',
    fields: ['dictDataId', 'dictLabel', 'dictValue', 'dictSort',
      'listClass', 'isDefault', 'status', 'createTime',
      'updateTime', 'createBy', 'updateBy'],
  });
  dictDataState.form.row.dictDataId = ''
  dictDataState.form.row.createTime = ''
  dictDataState.form.row.updateTime = ''
  dictDataState.form.row.createBy = ''
  dictDataState.form.row.updateBy = ''
}

const delDictData = (res: SysDictData) => {
  console.log('delDictData', res);

}

const dictDataDrawerClose = () => {
  dictDataState.form.row.dictType = ''
  console.log('dictDataState.form.row.dictType', dictDataState.form.row);

}

// ---------------------------------------

</script>

<style scoped></style>
